﻿using DmTools.Model;
using Microsoft.VisualBasic.FileIO;
using Newtonsoft.Json;
using NPOI.OpenXmlFormats.Spreadsheet;
using Tool.Helper;
using Tool.Helper.Dm;
using Tool.Model;

namespace DmTools
{
    public partial class MainWindow : Form
    {
        private readonly string EnableInfoFilePath = "Configs/FuncitonEnableInfoConfig.json";
        private readonly string SettingInfoFilePath = "Configs/SettingInfoConfig.json";
        private readonly string ItemInfoFilePath = "Configs/ItemInfoConfig.json";

        DmHelperEx _dm;
        private CancellationTokenSource _cts;
        private static bool _isRun = false;  //是否运行
        private FunctionEnableInfoEntity _funcitonEnableInfo = new FunctionEnableInfoEntity();  //各功能选择信息
        private SettingInfoEntity _settingInfo = new SettingInfoEntity();                       //设置信息
        private SizeEntity _windowSize = new SizeEntity();                                     //窗体大小信息
        private LocationEntity _location = new LocationEntity();                               //窗体位置信息
        private ReaderWriterLockSlim _itemInfoLock = new ReaderWriterLockSlim();


        private int _logCount;             //日志条数
        private int _runCount = 0;           //运行计数
        private int _planCount = 0;          //计划运行计数
        private DateTime _lastCountTime = DateTime.Now; //上次运行计数时时间
        private int _handler = 0;            //窗口句柄
        private bool _isLimitWin = true;     //是否限定窗口

        private GetColorListEntity _colorList = new GetColorListEntity();  //自定义抓点功能中颜色列表
        private Point _point = new Point();                                //自定义抓点功能中点
        private List<ItemInfoEntity> _itemInfoList = new List<ItemInfoEntity>();  //所有自定义语句列表
        public MainWindow()
        {

            InitializeComponent();
            _dm = new DmHelperEx();
            _cts = new CancellationTokenSource();
            var result = _dm.Init();
            if (!result)
            {
                MessageBox.Show("DM初始化失败！");
            }
            {
                #region  //快捷键
                HotKeyHelper.AddHotKey("btnStart", Keys.Shift | Keys.A, (s, e) =>
                {
                    btn_start_Click(null, null);
                    e.Handled = true;
                });
                HotKeyHelper.AddHotKey("btnCancel", Keys.Shift | Keys.S, (s, e) =>
                {
                    btn_cancel_Click(null, null);
                    e.Handled = true;
                });
                HotKeyHelper.AddHotKey("btnGetColor", Keys.Shift | Keys.X, (s, e) =>
                {
                    GetColor();
                    e.Handled = true;
                });
                HotKeyHelper.AddHotKey("btnGetPoint", Keys.Shift | Keys.Z, (s, e) =>
                {
                    GetPoint();
                    e.Handled = true;
                });
                #endregion
            }

            //日志处理
            _dm.AddLogEvent += AddLog;

        }

        /// <summary>
        /// 开始任务
        /// </summary>
        /// <param name="token"></param>
        public void StartTask(CancellationToken token)
        {
            DateTime lastTime = DateTime.Now;
            double contrast = 1.0;
            FindResultEntity result = new FindResultEntity();
            _handler = 0;
            while (!_cts.IsCancellationRequested && _isRun)
            {
                _isLimitWin = !string.IsNullOrEmpty(_settingInfo.WindowsName);
                if (_handler == 0 && _isLimitWin)
                {
                    _handler = _dm.FindWindow(_settingInfo.WindowsName);
                    SetWindowsSize();
                    //_dm.BindWindow(_handler);
                    SetText(tbx_info_winHandle, _handler.ToString());
                }
                if (_handler == 0 && _isLimitWin)
                {
                    Thread.Sleep(_settingInfo.CyclePeriod);
                    continue;
                }
                if (_isLimitWin && _funcitonEnableInfo.CheckWinSize)
                {
                    SetWindowsSize();
                }
                //对自定义找色数据进行遍历处理
                if (_itemInfoList != null && _itemInfoList.Any())
                {
                    _itemInfoLock.EnterReadLock();
                    try
                    {
                        contrast = _settingInfo.Contrast;
                        result.Result = false;
                        if (_isLimitWin && _location.Result) //判断是否限定窗口
                        {
                            foreach (var item in _itemInfoList)
                            {
                                if (item.ItemFiledCount == 11)   //11参数
                                {
                                    //需要判断对比度和轨迹是否启用
                                        
                                    if (!_funcitonEnableInfo.EnableContrast)
                                    {
                                        contrast = item.ItemFieldInfo.Sim;
                                    }
                                    result = _dm.FindColorClick(_location.LocationL.X + item.ItemFieldInfo.X1, _location.LocationL.Y + item.ItemFieldInfo.Y1,
                                        _location.LocationL.X + item.ItemFieldInfo.X2, _location.LocationL.Y + item.ItemFieldInfo.Y2,
                                           item.ItemFieldInfo.ColorFirst, item.ItemFieldInfo.ColorOffset,
                                           item.ItemFieldInfo.PreDelay, item.ItemFieldInfo.PostDelay,
                                           contrast, _funcitonEnableInfo.EnableMoveTrack, item.ItemFieldInfo.LogStr, _settingInfo.FloatX, _settingInfo.FloatY);
                                }
                                else    //15参数      
                                {
                                    result = _dm.FindColorClickRange(_location.LocationL.X + item.ItemFieldInfo.X1, _location.LocationL.Y + item.ItemFieldInfo.Y1,
                                        _location.LocationL.X + item.ItemFieldInfo.X2, _location.LocationL.Y + item.ItemFieldInfo.Y2,
                                            item.ItemFieldInfo.ColorFirst, item.ItemFieldInfo.ColorOffset,
                                            _location.LocationL.X + item.ItemFieldInfo.XX1, _location.LocationL.Y + item.ItemFieldInfo.YY1,
                                            _location.LocationL.X + item.ItemFieldInfo.XX2, _location.LocationL.Y + item.ItemFieldInfo.YY2,
                                              item.ItemFieldInfo.PreDelay, item.ItemFieldInfo.PostDelay,
                                               contrast, _funcitonEnableInfo.EnableMoveTrack, item.ItemFieldInfo.LogStr, _settingInfo.FloatX, _settingInfo.FloatY);
                                }

                                if (result.Result)
                                {
                                    _runCount++;
                                    SetText(tbx_info_runCount, _runCount.ToString());
                                    int sec = Convert.ToInt32((DateTime.Now - _lastCountTime).TotalSeconds);
                                    SetText(tbx_info_singleDuration, sec.ToString()+" s");
                                    _lastCountTime = DateTime.Now;
                                    if (_planCount > 0 && _runCount >= _planCount)
                                    {
                                        _isRun = false;
                                        if (_funcitonEnableInfo.IsPlanCompleteShutdown)
                                        {
                                            ShutdownHelper.ShutdownNowDelaySecond();
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            foreach (var item in _itemInfoList)
                            {
                                if (item.ItemFiledCount == 11)   //11参数
                                {
                                    //需要判断对比度和轨迹是否启用

                                    if (!_funcitonEnableInfo.EnableContrast)
                                    {
                                        contrast = item.ItemFieldInfo.Sim;
                                    }
                                    result = _dm.FindColorClick(item.ItemFieldInfo.X1, item.ItemFieldInfo.Y1, item.ItemFieldInfo.X2, item.ItemFieldInfo.Y2,
                                           item.ItemFieldInfo.ColorFirst, item.ItemFieldInfo.ColorOffset,
                                           item.ItemFieldInfo.PreDelay, item.ItemFieldInfo.PostDelay,
                                           contrast, _funcitonEnableInfo.EnableMoveTrack, item.ItemFieldInfo.LogStr, _settingInfo.FloatX, _settingInfo.FloatY);
                                }
                                else    //15参数
                                {
                                    result = _dm.FindColorClickRange(item.ItemFieldInfo.X1, item.ItemFieldInfo.Y1, item.ItemFieldInfo.X2, item.ItemFieldInfo.Y2,
                                            item.ItemFieldInfo.ColorFirst, item.ItemFieldInfo.ColorOffset,
                                             item.ItemFieldInfo.XX1, item.ItemFieldInfo.YY1, item.ItemFieldInfo.XX2, item.ItemFieldInfo.YY2,
                                              item.ItemFieldInfo.PreDelay, item.ItemFieldInfo.PostDelay,
                                               contrast, _funcitonEnableInfo.EnableMoveTrack, item.ItemFieldInfo.LogStr, _settingInfo.FloatX, _settingInfo.FloatY);
                                }

                                if (result.Result)
                                {
                                    _runCount++;
                                    SetText(tbx_info_runCount, _runCount.ToString());
                                    int sec = Convert.ToInt32((DateTime.Now - _lastCountTime).TotalSeconds);
                                    SetText(tbx_info_singleDuration, sec.ToString() + " s");
                                    _lastCountTime = DateTime.Now;
                                    if (_planCount > 0 && _runCount >= _planCount)
                                    {
                                        _isRun = false;
                                        if (_funcitonEnableInfo.IsPlanCompleteShutdown)
                                        {
                                            ShutdownHelper.ShutdownNowDelaySecond();
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                    }
                    finally
                    {
                        _itemInfoLock.ExitReadLock();
                    }
                }

                SetText(tbx_info_cycleDuration, (Convert.ToInt32((DateTime.Now - lastTime).TotalMilliseconds)).ToString() + " ms");
                lastTime = DateTime.Now;
                Thread.Sleep(_settingInfo.CyclePeriod);
            }
            SetEnbale(btn_cancel, false);
            SetEnbale(btn_start, true);
        }

        /// <summary>
        /// 结束任务
        /// </summary>
        public void StopTask()
        {
            _isRun = false;
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            //初始化配置
            _funcitonEnableInfo = JsonHelper.ReadData<FunctionEnableInfoEntity>(EnableInfoFilePath);
            if (_funcitonEnableInfo != null)
            {
                this.cbx_contrast.Checked = _funcitonEnableInfo.EnableContrast;
                this.cbx_logNewestSelected.Checked = _funcitonEnableInfo.EnableLogNewestSelected;
                this.cbx_checkWinSize.Checked = _funcitonEnableInfo.CheckWinSize;
                this.cbx_colorCast.Checked = _funcitonEnableInfo.EnableColorCast;
                this.cbx_moveTrack.Checked = _funcitonEnableInfo.EnableMoveTrack;
                this.cbx_openRun.Checked = _funcitonEnableInfo.IsOpenRun;
                this.cbx_planCompleteShutdown.Checked = _funcitonEnableInfo.IsPlanCompleteShutdown;

            }
            else
            {
                _funcitonEnableInfo = new FunctionEnableInfoEntity();
            }
            _settingInfo = JsonHelper.ReadData<SettingInfoEntity>(SettingInfoFilePath);
            if (_settingInfo != null)
            {
                SetSettingInfo(_settingInfo);
            }
            else
            {
                _settingInfo = new SettingInfoEntity();
                btn_setting_save_Click(null, null);
            }

            //初始化找色语句和自定义列表
            _itemInfoList = JsonHelper.ReadData<List<ItemInfoEntity>>(ItemInfoFilePath);
            if (_itemInfoList != null)
            {
                if (_itemInfoList.Any())
                {
                    if (_funcitonEnableInfo != null && _funcitonEnableInfo.EnableColorCast)
                    {
                        _itemInfoList.ForEach(p => p.Init(_settingInfo?.ColorCast));
                    }
                    else
                    {
                        _itemInfoList.ForEach(p => p.Init());
                    }
                    ltb_cus_items.Items.Clear();
                    foreach (var item in _itemInfoList)
                    {
                        ltb_cus_items.Items.Add(item.ItemStr);
                    }
                }

            }
            else
            {
                _itemInfoList = new List<ItemInfoEntity>();
            }
            ltb_cus_items.SelectedIndex = -1;
            cbx_cus_funcitonChoose.SelectedIndex = 0;

            //打开时是否自动运行判断
            if (_funcitonEnableInfo != null && _funcitonEnableInfo.IsOpenRun)
            {
                this.WindowState = FormWindowState.Minimized;
                btn_start_Click(null, null);
            }


        }

        private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            _cts.Cancel();
            _dm.Dm.Close();
        }
        private void btn_test_Click(object sender, EventArgs e)
        {
            //var stObj = Keys.Shift | Keys.Z;
            //var str= JsonConvert.SerializeObject(stObj);
            //var s = JsonConvert.DeserializeObject<Keys>(str);
            //_dm.MoveTrack(100, 100);
            //_dm.MoveTrackEx(100, 100);
            //ShutdownHelper.ShutdownNowDelaySecond();
            //var re = _dm.FindColorExist(0, 0, 600, 400, "000000-020202", "-1|35|000000|020202,47|-2|000000|020202", 1,1, "测试是否找到");
            //if (re.Result)
            //{
            //    if (_funcitonEnableInfo.EnableMoveTrack)
            //    {
            //        _dm.MoveTrack(re.PointInfo);
            //    }
            //    else
            //    {
            //        _dm.MoveTo(re.PointInfo);
            //    }
            //}
            //DateTime dt = DateTime.Now;
            //List<ItemInfoEntity> list = new List<ItemInfoEntity>();
            //list.Add(new ItemInfoEntity
            //{
            //    ItemStr = "0, 0, 600, 400, \"000000-020202\", \"-1|35|000000|020202,47|-2|000000|020202\", 1, 500,3000,1,测试1"
            //});
            //list.Add(new ItemInfoEntity
            //{
            //    ItemStr = "0, 0, 600, 400, \"000000-020202\", \"-1|35|000000|020202,47|-2|000000|020202\",100,100,200,200, 1, 500,3000,1,测试2"
            //});
            //list.ForEach(p => p.Init());
            //JsonHelper.SaveData(list, ItemInfoFilePath);
        }


        #region   //基础方法

        /// <summary>
        ///  获取窗体坐标和设置窗体大小
        /// </summary>
        /// <param name="isSetSize"></param>
        /// <returns></returns>
        public LocationEntity SetWindowsSize()
        {
            _location = _dm.GetWindowRect(_handler);
            if (_location.Result)
            {
                _windowSize.Width = _location.LocationR.X - _location.LocationL.X;
                _windowSize.Height = _location.LocationR.Y - _location.LocationL.Y;
                if (_windowSize.Width != _settingInfo.WindowsWidth || _windowSize.Height != _settingInfo.WindowsHeight)
                {
                    _dm.SetWindowSize(_settingInfo.WindowsWidth, _settingInfo.WindowsHeight);
                }
            }
            return _location;
        }

        /// <summary>
        /// 设置控件文本
        /// </summary>
        /// <param name="textBox"></param>
        /// <param name="str"></param>
        private void SetText(Control textBox, string str)
        {
            textBox.Invoke(() =>
            {
                textBox.Text = str;
            });
        }

        /// <summary>
        /// 设置控件使能
        /// </summary>
        /// <param name="cl"></param>
        /// <param name="isEnable"></param>
        private void SetEnbale(Control cl, bool isEnable)
        {
            cl.Invoke(() =>
            {
                cl.Enabled = isEnable;
            });
        }


        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="str"></param>
        public void AddLog(string str)
        {
            this.lbox_info_log.Invoke(() =>
            {
                lbox_info_log.Items.Add("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + str);
                if (lbox_info_log.Items.Count > 1000)
                {
                    lbox_info_log.Items.RemoveAt(0);
                }
                _logCount = lbox_info_log.Items.Count;
                if (_funcitonEnableInfo.EnableLogNewestSelected)
                {
                    lbox_info_log.SelectedIndex = lbox_info_log.Items.Count - 1;
                }
            });
            SetText(tbx_info_logCount, _logCount.ToString());
            LogHelper.LogInfo(str);
        }

        /// <summary>
        /// 自定义抓色功能
        /// </summary>
        public void GetColor()
        {
            var result = _dm.GetCursorPos();
            if (result.Result)
            {
                _colorList.List.Add(new GetColorEntity
                {
                    ColorStr = _dm.GetColor(result.PointInfo.X, result.PointInfo.Y),
                    Location = result.PointInfo,
                    ColorCastStr = tbx_cus_colorCast.Text.Trim()
                });
            }
            _colorList.Init();
            tbx_cus_getColor.Text = _colorList.FirstColorStr;
            if (!string.IsNullOrEmpty(_colorList.OtherColorStr))
            {
                tbx_cus_getColor.Text += "," + _colorList.OtherColorStr;
            }
        }

        /// <summary>
        /// 自定义抓点功能
        /// </summary>
        public void GetPoint()
        {

            if (!string.IsNullOrEmpty(_settingInfo.WindowsName) && cbx_cus_limitWin.Checked)
            {
                var data = new LocationEntity();
                _handler = _dm.FindWindow(_settingInfo.WindowsName);
                data = SetWindowsSize();
                var result = _dm.GetCursorPos();
                if (result.Result && data.Result)
                {
                    _point = new Point(result.PointInfo.X - data.LocationL.X, result.PointInfo.Y - data.LocationL.Y);
                    SetText(tbx_cus_getPoint, _point.X.ToString() + "," + _point.Y.ToString());
                }
            }
            else
            {
                var result = _dm.GetCursorPos();
                if (result.Result)
                {
                    _point = new Point(result.PointInfo.X, result.PointInfo.Y);
                    SetText(tbx_cus_getPoint, _point.X.ToString() + "," + _point.Y.ToString());
                }
            }

        }

        #endregion

        #region  //首页功能按钮界面元素

        private void btn_clearLog_Click(object sender, EventArgs e)
        {
            this.tbx_info_logCount.Text = "";
            this.lbox_info_log.Items.Clear();
        }


        /// <summary>
        /// 开始按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_start_Click(object sender, EventArgs e)
        {
            lock (this)
            {
                if (_isRun)
                {
                    return;
                }

                if (!string.IsNullOrEmpty(tbx_info_planCount.Text.Trim()))
                {
                    if (!int.TryParse(tbx_info_planCount.Text.Trim(), out _planCount))
                    {
                        MessageBox.Show("计划次数不能正确的转换成整数！");
                        return;
                    }
                }
                else
                {
                    _planCount = 0;
                }
                _isRun = true;
            }
            btn_start.Enabled = false;
            btn_cancel.Enabled = true;
            if (_settingInfo == null)
            {
                _settingInfo = new SettingInfoEntity();
                btn_setting_save_Click(null, null);
            }
            Task.Run(() => StartTask(_cts.Token));
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            StopTask();
        }


        private void btn_reset_Click(object sender, EventArgs e)
        {
            _runCount = 0;
            _handler = 0;
            tbx_info_winHandle.Text = "";
            tbx_info_runCount.Text = "";
            tbx_info_singleDuration.Text = "";
            tbx_info_planCount.Text = "";
            tbx_info_cycleDuration.Text = "";

        }

        private void btn_relocation_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(_settingInfo.WindowsName))
            {
                var handle = _dm.FindWindow(_settingInfo.WindowsName);
                _dm.MoveWindow(0, 0, handle);
            }

        }
        #endregion

        #region  //设置功能界面元素
        private void btn_setting_save_Click(object sender, EventArgs e)
        {
            _settingInfo.WindowsName = this.tbx_setting_winName.Text;
            _settingInfo.WindowsHeight = Convert.ToInt32(this.tbx_setting_winHeight.Text);
            _settingInfo.WindowsWidth = Convert.ToInt32(this.tbx_setting_winWidth.Text);
            _settingInfo.Contrast = Convert.ToDouble(this.tbx_setting_contrast.Text);
            _settingInfo.CyclePeriod = Convert.ToInt32(this.tbx_setting_cyclePeriod.Text);
            _settingInfo.ColorCast = this.tbx_setting_colorCast.Text;
            _settingInfo.FloatX = Convert.ToInt32(this.tbx_setting_floatX.Text);
            _settingInfo.FloatY = Convert.ToInt32(this.tbx_setting_floatY.Text);
            if (JsonHelper.SaveData(_settingInfo, SettingInfoFilePath))
            {
                MessageBox.Show("保存窗口设置成功！");
            }
        }

        private void btn_setting_getWinSize_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbx_setting_winName.Text))
            {
                return;
            }
            var handle = _dm.FindWindow(this.tbx_setting_winName.Text);
            var result = _dm.GetWindowSize(handle);
            if (result.Result)
            {
                this.tbx_setting_winWidth.Text = result.Width.ToString();
                this.tbx_setting_winHeight.Text = result.Height.ToString();
            }

        }

        private void btn_setting_restore_Click(object sender, EventArgs e)
        {
            SetSettingInfo(_settingInfo);
        }

        private void SetSettingInfo(SettingInfoEntity data)
        {
            if (data != null)
            {
                this.tbx_setting_winName.Text = data.WindowsName;
                this.tbx_setting_winHeight.Text = data.WindowsHeight.ToString();
                this.tbx_setting_winWidth.Text = data.WindowsWidth.ToString();
                this.tbx_setting_contrast.Text = data.Contrast.ToString();
                this.tbx_setting_cyclePeriod.Text = data.CyclePeriod.ToString();
                this.tbx_setting_colorCast.Text = data.ColorCast;
                this.tbx_setting_floatX.Text = data.FloatX.ToString();
                this.tbx_setting_floatY.Text = data.FloatY.ToString();
            }
        }

        #endregion

        #region  //功能复选框功能界面元素
        private void btn_saveEnable_Click(object sender, EventArgs e)
        {
            _funcitonEnableInfo.EnableContrast = this.cbx_contrast.Checked;
            _funcitonEnableInfo.EnableLogNewestSelected = this.cbx_logNewestSelected.Checked;
            _funcitonEnableInfo.CheckWinSize = this.cbx_checkWinSize.Checked;
            _funcitonEnableInfo.EnableColorCast = this.cbx_colorCast.Checked;
            _funcitonEnableInfo.EnableMoveTrack = this.cbx_moveTrack.Checked;
            _funcitonEnableInfo.IsOpenRun = this.cbx_openRun.Checked;
            _funcitonEnableInfo.IsPlanCompleteShutdown = this.cbx_planCompleteShutdown.Checked;

            if (JsonHelper.SaveData(_funcitonEnableInfo, EnableInfoFilePath))
            {
                MessageBox.Show("保存功能选项成功！");
            }

        }
        private void cbx_winTop_CheckedChanged(object sender, EventArgs e)
        {
            this.TopMost = ((CheckBox)sender).Checked;
        }
        private void cbx_checkWinSize_CheckedChanged(object sender, EventArgs e)
        {
            _funcitonEnableInfo.CheckWinSize = this.cbx_checkWinSize.Checked;
        }
        private void cbx_planCompleteShutdown_CheckedChanged(object sender, EventArgs e)
        {
            _funcitonEnableInfo.IsPlanCompleteShutdown = this.cbx_planCompleteShutdown.Checked;
        }
        private void cbx_logNewestSelected_CheckedChanged(object sender, EventArgs e)
        {
            _funcitonEnableInfo.EnableLogNewestSelected = this.cbx_logNewestSelected.Checked;
        }
        private void cbx_moveTrack_CheckedChanged(object sender, EventArgs e)
        {
            _funcitonEnableInfo.EnableMoveTrack = this.cbx_moveTrack.Checked;
        }
        private void btn_cancelShutdown_Click(object sender, EventArgs e)
        {
            ShutdownHelper.CancelShutdown();
        }


        private void cbx_colorCast_CheckedChanged(object sender, EventArgs e)
        {
            _funcitonEnableInfo.EnableColorCast = this.cbx_colorCast.Checked;
            if (_funcitonEnableInfo.EnableColorCast && _settingInfo != null)
            {

                _itemInfoList.ForEach(p => p.Init(_settingInfo.ColorCast));
            }
            else
            {
                _itemInfoList.ForEach(p => p.Init());
            }
        }
        private void cbx_contrast_CheckedChanged(object sender, EventArgs e)
        {
            _funcitonEnableInfo.EnableContrast = this.cbx_contrast.Checked;
        }

        #endregion

        #region  //自定义功能界面元素


        private void btn_cus_saveItem_Click(object sender, EventArgs e)
        {
            try
            {
                _itemInfoLock.EnterWriteLock();
                _itemInfoList.Clear();
                if (ltb_cus_items.Items.Count > 0)
                {
                    foreach (var item in ltb_cus_items.Items)
                    {
                        _itemInfoList.Add(new ItemInfoEntity
                        {
                            ItemStr = item?.ToString()
                        });
                    }
                    if (_funcitonEnableInfo.EnableColorCast && _settingInfo != null)
                    {
                        _itemInfoList.ForEach(p => p.Init(_settingInfo.ColorCast));
                    }
                    else
                    {
                        _itemInfoList.ForEach(p => p.Init());
                    }
                }
                if (JsonHelper.SaveData(_itemInfoList, ItemInfoFilePath))
                {
                    MessageBox.Show("保存点位信息成功！");
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex);
            }
            finally
            {
                _itemInfoLock.ExitWriteLock();
            }

        }

        private void btn_cus_magnifyGlass_Click(object sender, EventArgs e)
        {
            MagnifierForm mf = new MagnifierForm();
            mf.Show();
        }
        GetColorTool colorTool;
        private void btn_cus_getColorTool_Click(object sender, EventArgs e)
        {
            colorTool = new GetColorTool();
            colorTool.Show();
        }
        private void btn_cus_addItem_Click(object sender, EventArgs e)
        {

            List<string> itemFields = new List<string>();
            var str = tbx_cus_code.Text.Trim();
            if (string.IsNullOrEmpty(str) || !str.Contains(","))
            {
                return;
            }
            using (var parser = new TextFieldParser(new System.IO.StringReader(str)))
            {
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");
                parser.HasFieldsEnclosedInQuotes = true; // 关键：识别引号内的内容
                itemFields.AddRange(parser.ReadFields()); // 可选：去除空格
            }
            int tempInt;
            double tempDouble;
            //添加时判断参数个数，并判断参数类型是否符合，不符合提示
            if (itemFields.Count == 11)  //11参数
            {
                bool isCucess = int.TryParse(itemFields[0], out tempInt) &&
                    int.TryParse(itemFields[1], out tempInt) &&
                    int.TryParse(itemFields[2], out tempInt) &&
                    int.TryParse(itemFields[3], out tempInt) &&
                    double.TryParse(itemFields[6], out tempDouble) &&
                     int.TryParse(itemFields[7], out tempInt) &&
                      int.TryParse(itemFields[8], out tempInt) &&
                       int.TryParse(itemFields[9], out tempInt);
                if (!isCucess)
                {
                    MessageBox.Show("参数类型不匹配不对！");
                    return;
                }
            }
            else if (itemFields.Count == 15)  //15参数
            {
                bool isCucess = int.TryParse(itemFields[0], out tempInt) &&
                   int.TryParse(itemFields[1], out tempInt) &&
                   int.TryParse(itemFields[2], out tempInt) &&
                   int.TryParse(itemFields[3], out tempInt) &&
                   int.TryParse(itemFields[6], out tempInt) &&
                   int.TryParse(itemFields[7], out tempInt) &&
                   int.TryParse(itemFields[8], out tempInt) &&
                   int.TryParse(itemFields[9], out tempInt) &&
                   double.TryParse(itemFields[10], out tempDouble) &&
                   int.TryParse(itemFields[11], out tempInt) &&
                   int.TryParse(itemFields[12], out tempInt) &&
                   int.TryParse(itemFields[13], out tempInt);
                if (!isCucess)
                {
                    MessageBox.Show("参数类型不匹配不对！");
                    return;
                }
            }
            else
            {
                MessageBox.Show("参数个数不对！");
                return;
            }

            ltb_cus_items.Items.Add(str);
            tbx_cus_code.Text = "";
        }
        private void btn_cus_addDeaultPrm_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbx_cus_code.Text))
            {
                tbx_cus_code.Text += ",";
            }
            if (cbx_cus_funcitonChoose.SelectedIndex == 0)  //多点找色
            {
                tbx_cus_code.Text += "0.98,500,2000,1,测试1";
            }
            else if (cbx_cus_funcitonChoose.SelectedIndex == 1)  //多点找色指定范围
            {
                tbx_cus_code.Text += "0.98,500,2000,1,测试1";
            }
        }

        private void ltb_cus_items_DoubleClick(object sender, EventArgs e)
        {
            if (ltb_cus_items.SelectedIndex >= 0)
            {
                lbl_cus_items_chooseIndex.Text = "选中项:" + ltb_cus_items.SelectedIndex.ToString();
                tbx_cus_code.Text = ltb_cus_items.Items[ltb_cus_items.SelectedIndex].ToString();
            }
            else
            {
                lbl_cus_items_chooseIndex.Text = "选中项:";
            }
        }
        private void btn_cus_removeLastColor_Click(object sender, EventArgs e)
        {
            if (_colorList.List.Any())
            {
                _colorList.List.RemoveAt(_colorList.List.Count() - 1);
            }
            _colorList.Init();
            tbx_cus_getColor.Text = _colorList.FirstColorStr;
            if (!string.IsNullOrEmpty(_colorList.OtherColorStr))
            {
                tbx_cus_getColor.Text += "," + _colorList.OtherColorStr;
            }
        }
        private void btn_cus_reset_Click(object sender, EventArgs e)
        {
            ltb_cus_items.Items.Clear();
            if (_itemInfoList != null && _itemInfoList.Any())
            {
                foreach (var item in _itemInfoList)
                {
                    ltb_cus_items.Items.Add(item.ItemStr);
                }
            }

        }
        private void btn_cus_clearColor_Click(object sender, EventArgs e)
        {
            tbx_cus_getColor.Text = "";
            _colorList.List.Clear();
            _colorList.FirstColorStr = "";
            _colorList.OtherColorStr = "";
        }
        private void ltb_cus_items_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void tbx_cus_codeClear_Click(object sender, EventArgs e)
        {
            this.tbx_cus_code.Text = "";
        }
        private void btn_cus_deleteItem_Click(object sender, EventArgs e)
        {
            if (ltb_cus_items.SelectedIndex >= 0)
            {
                ltb_cus_items.Items.RemoveAt(ltb_cus_items.SelectedIndex);
            }
            if (ltb_cus_items.SelectedIndex >= 0)
            {
                lbl_cus_items_chooseIndex.Text = "选中项:" + ltb_cus_items.SelectedIndex.ToString();
            }
            else
            {
                lbl_cus_items_chooseIndex.Text = "选中项:";
            }
        }
        private void btn_cus_copyColor_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.tbx_cus_getColor.Text) || _colorList.List.Count <= 1)
            {
                return;
            }
            _dm.Dm.SetClipboard(this.tbx_cus_getColor.Text);
            tbx_cus_codeAddTxt(this.tbx_cus_getColor.Text);
            this.tbx_cus_getColor.Text = "";
            btn_cus_clearColor_Click(null, null);
        }
        private void btn_cus_copyPoint_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.tbx_cus_getPoint.Text))
            {
                return;
            }
            _dm.Dm.SetClipboard(this.tbx_cus_getPoint.Text);
            tbx_cus_codeAddTxt(this.tbx_cus_getPoint.Text);
            this.tbx_cus_getPoint.Text = "";

        }
        private void tbx_cus_codeAddTxt(string str)
        {
            if (!string.IsNullOrEmpty(tbx_cus_code.Text) && !tbx_cus_code.Text.EndsWith(","))
            {
                tbx_cus_code.Text += ",";
            }
            tbx_cus_code.Text += str;
        }

        #endregion

        private void tbx_info_planCount_TextChanged(object sender, EventArgs e)
        {

            if (!string.IsNullOrEmpty(tbx_info_planCount.Text.Trim()))
            {
                if (!int.TryParse(tbx_info_planCount.Text.Trim(), out _planCount))
                {
                    _planCount = 0;
                    return;
                }
            }
            else
            {
                _planCount = 0;
            }
        }
    }
}
